package com.system.outpatientsystem.service.impl;

import com.system.outpatientsystem.DTO.AppointmentDTO;
import com.system.outpatientsystem.DTO.RegistrationDTO;
import com.system.outpatientsystem.mapper.AppointmentMapper;
import com.system.outpatientsystem.mapper.DoctorMapper;
import com.system.outpatientsystem.mapper.RegistrationMapper;
import com.system.outpatientsystem.pojo.Doctor;
import com.system.outpatientsystem.pojo.Result;
import com.system.outpatientsystem.pojo.appointment_table;
import com.system.outpatientsystem.pojo.registration_table;
import com.system.outpatientsystem.service.RegistrationService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class RegistrationServiceImpl implements RegistrationService {

    @Autowired
    private RegistrationMapper registrationMapper;
    @Autowired
    private AppointmentMapper appointmentMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private DoctorMapper doctorMapper;
    @Override
    public void createRegistration(Integer doctorId, Integer userId) {
        String doctorQueue="queue"+doctorId.toString();
       //查询是否有预约
        List<appointment_table> appointmentTables=appointmentMapper.findByuserId(userId);

        //无预约入队
        if(appointmentTables.isEmpty()){
            redisTemplate.opsForList().rightPush(doctorQueue,userId);
        }else {


            insertUserRandomly(doctorQueue,userId);

        }

        //直接末尾入队

        List<Integer> yourQueueContents = redisTemplate.opsForList().range(doctorQueue, 0, -1);
        System.out.println(doctorQueue+" Contents: " + yourQueueContents);
        registrationMapper.createtable(doctorId,userId);
    }

    @Override
    public Integer getPosition(Integer doctorId, Integer userId) {

        String doctorQueue="queue"+doctorId.toString();
        // 获取队列中所有用户
        List<Integer> queueContents = redisTemplate.opsForList().range(doctorQueue, 0, -1);

        // 判断队列是否为空
        if (queueContents == null || queueContents.isEmpty()) {
            return  -1;
        }

        // 获取用户在队列中的位置
        Integer userPosition = queueContents.indexOf(userId);

        // 判断用户是否存在于队列中
        if (userPosition == -1) {
            return -1;
        }

        // 返回用户在队列中的位置
        return userPosition;
    }

    @Override
    public Integer defaultLeaveQueue(Integer doctorId) {
        String doctorQueue="queue"+doctorId.toString();

        Integer userId=(Integer) redisTemplate.opsForList().leftPop(doctorQueue);
        System.out.println("离队患者:"+userId);
        return  userId;
    }

    @Override
    public List<RegistrationDTO> list(Integer userId) {
        List<registration_table> tablelist = registrationMapper.list(userId);
        List<RegistrationDTO> dtos=new ArrayList<>();
        for(registration_table registrationTable:tablelist){
            RegistrationDTO registrationDTO=new RegistrationDTO();
            Integer doctorId=registrationTable.getDoctorId();

            Doctor doctor =doctorMapper.findById(doctorId);
            registrationDTO.setRegistrationTable(registrationTable);
            registrationDTO.setDoctor(doctor);
            dtos.add(registrationDTO);
        }
        return dtos;
    }


    public void insertUserRandomly(String yourQueue, Integer userId) {
        // 获取队列中所有用户
        List<Integer> queueContents = redisTemplate.opsForList().range(yourQueue, 0, -1);

        // 生成随机插入位置（范围在3到10之间）
        int randomPosition = (int) (Math.random() * (7)) + 3;

        // 如果队列长度不足以容纳随机位置，将随机位置设置为队列末尾
        if (randomPosition > queueContents.size()) {
            randomPosition = queueContents.size();
        }

        // 在队列中插入用户ID到随机位置
        queueContents.add(randomPosition, userId);
        redisTemplate.delete(yourQueue);

        // 更新Redis队列
        redisTemplate.opsForList().rightPushAll(yourQueue, queueContents);


    }
}
